//
//  Utilities.m
//  ZYD
//
//  Created by chenxin on 16/3/10.
//  Copyright © 2016年 Chinaj. All rights reserved.
//

#import "Utilities.h"

@implementation Utilities

+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}



//取消searchbar背景色
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark - 判断字符串是否为空
+ (BOOL)isEmpty:(NSString *)string
{
    if (string == nil || [string isEqual:[NSNull null]] || string.length <= 0 || [string isEqualToString:@""] || [string isEqualToString:@"null"] || [string isEqualToString:@"<null>"]) {
        return YES;
    }
    
    return NO;
}

#pragma mark - 将nil、NSNull转成空字符串
+ (NSString *)safeString:(NSString *)string
{
    if (string == nil || [string isEqual:[NSNull null]] || string.length <= 0 || [string isEqualToString:@""]) {
        return @"";
    }
    
    return string;
}

#pragma mark - 判断手机号码
+ (BOOL)checkTelephoneNumber:(NSString*)number
{
    if ([number length] == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码!"];
        return NO;
    }
    NSString *regex = @"^1\\d{10}$";//@"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";//@"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:number];
    if (!isMatch) {
        //        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入正确的手机号码" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        //        [alert show];
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码!"];
        return NO;
    }
    return YES;
}

#pragma mark - 验证邮箱
+ (BOOL)validateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

#pragma mark - 验证密码
+ (BOOL)validatePassword:(NSString *)password {
    //必须包含数字、字母大小写、特殊字符组合 6-20位
    NSString *passWordRegex = @"^.{6,20}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passWordRegex];
    BOOL isMatch = [passWordPredicate evaluateWithObject:password];
    if (!isMatch) {
//        [SVProgressHUD showErrorWithStatus:ValidatePassword_Error];
        return NO;
    }
    return YES;
}




#pragma mark - 时间转为yyyyMMddHHMMss
+ (NSString *)dateConverString
{
    NSTimeInterval timeSp =  [[NSDate  date] timeIntervalSince1970];
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyyMMddHHMMss"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timeSp];
    
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    return confromTimespStr;
    
}

#pragma mark - 两个NSDate相减
+ (NSTimeInterval)twoDateSub:(NSDate *)beginDate andEndDate:(NSDate *)endDate
{
    NSTimeInterval time = [endDate timeIntervalSinceDate:beginDate];
    return time;
}

#pragma mark - Base64 ->UIImage
+ (UIImage *)base64CovertToUIImage:(NSString *)base64
{
    NSData *imageData = [[NSData alloc] initWithBase64EncodedString:base64 options:0];
    UIImage *image = [UIImage imageWithData:imageData];
    return image;
}

#pragma mark - NSDictionary -> Json String
+ (NSString*)dataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}


#pragma mark - 跳转AppStore
+ (void)skipToAppstore:(NSString *)storeUrl
{
    NSURL *url = [NSURL URLWithString:storeUrl];
    
    [[UIApplication sharedApplication] openURL:url];

}

#pragma mark - 强制闪退
+ (void)makeCrash
{
    NSArray *crashArray = @[];
    NSLog(@"%@", crashArray[2]);
    
}

#pragma mark - 返回跳转的地址
+ (NSString *)getPushUrlFrom:(NSString *)string suffixString:(NSString *)suffixStr
{
    if ( string.length <= 0 ) {
        return string;
    }
    
    if ( [string rangeOfString:@"m.onlyou.com"].location != NSNotFound ) {
        string = @"www.onlyou.com/onlyou-weixin/";
    }
    
    //先判断 是否有http
    if ( [string rangeOfString:@"http"].location != NSNotFound ) {
        //有http
        
    } else {
        //无http
        string = [NSString stringWithFormat:@"http://%@", string];
    }
    
    //判断最后一个字符是否是 /
    NSString *lastStr = [string substringFromIndex:string.length-1];
    if ( [lastStr rangeOfString:@"/"].location != NSNotFound ) {
        //有 /
    } else {
        //无 /
        string = [NSString stringWithFormat:@"%@/", string];
    }
    
    string = [NSString stringWithFormat:@"%@%@",string, suffixStr];
    
    return string;
}

#pragma mark - UserAgent
+ (void)setUserAgent:(NSString *)userAgentContent
{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUserAgent = [userAgent stringByAppendingString:userAgentContent];//自定义需要拼接的字符串
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - Tips 新手指引
+ (void)canShowTipsGuideView:(void(^)(void))show
{
    NSString *currentVersion = [[NSUserDefaults standardUserDefaults] objectForKey:AppVersion];
    if ( [Utilities isEmpty:currentVersion] || ![currentVersion isEqualToString:AppVersion] ) {
        //为空
        show();
        [[NSUserDefaults standardUserDefaults] setObject:AppVersion forKey:AppVersion];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark - 获取当前时间戳 （以毫秒为单位）
+(NSString *)getNowTimeTimestamp3{
    
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}




@end
